﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Qiniu.Storage;
using SmartWMS.Common.Extensions;
using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.Base;
using SmartWMS.Domain.BasicsDatum;
using SmartWMS.Domain.BusinessManage;
using SmartWMS.Domain.SystemSet;
using SmartWMS.EntityFramework;
using SmartWMS.Server.BasicsDatumServer.CustomerManagementService.Dto;
using SmartWMS.Server.BasicsDatumServer.WarehouseManagementService.Dto;
using SmartWMS.Server.BusinessServer.SalesManagementService.Dto;
using SmartWMS.Server.BusinessServer.SalesReturns;
using SmartWMS.Server.Repository;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartWMS.Server.BusinessServer.SalesManagementService
{
	/// <summary>
	/// 销售管理
	/// </summary>
	public class SalesManagementService : ISalesManagementService
	{
		private readonly IRepository<Product> _productRepository;
		private readonly IRepository<SalesManagement> _salesManagementRepository;
		private readonly IRepository<SalesManageDetail> _salesManageDetailRepository;
		private readonly IRepository<Custom> _customerRepository;
		private readonly IRepository<CustomContact> _customContactRepository;
		private readonly SmartWMSContext Db;
		private readonly IRepository<SalesReturn> _salesReturnRepository;

		public SalesManagementService(IRepository<Product> productRepository, IRepository<SalesManagement> salesManagementRepository, IRepository<SalesManageDetail> salesManageDetailRepository, SmartWMSContext db, IRepository<Custom> customerRepository, IRepository<CustomContact> customContactRepository, IRepository<SalesReturn> salesReturnRepository)
		{
			_productRepository = productRepository;
			_salesManagementRepository = salesManagementRepository;
			_salesManageDetailRepository = salesManageDetailRepository;
			Db = db;
			_customerRepository = customerRepository;
			_customContactRepository = customContactRepository;
			_salesReturnRepository = salesReturnRepository;
		}

		/// <summary>
		/// 显示销售管理
		/// </summary>
		/// <param name="dto">要查询的Dto对象</param>
		/// <returns></returns>
		public async Task<(int pageCount, int totalCount, Response<List<SalesManagementDtoInpute>> data)> GetSalesManagementDtoAsync(SearchSalesManagementDto dto)
		{
			try
			{
				var productList = await _productRepository.GetAllListAsync();
				var salesManagementList = await _salesManagementRepository.GetAllListAsync();
				var salesManageDetailList = await _salesManageDetailRepository.GetAllListAsync();

				var list = (from salesManagement in salesManagementList
							join salesManageDetail in salesManageDetailList
							on salesManagement.SalesCode equals salesManageDetail.SalesCode
							join product in productList
							on salesManageDetail.ProductId equals product.Id
							select new SalesManagementDtoInpute
							{
								SalesCode = salesManagement.SalesCode,
								ProductName = product.ProductName,
								ProductCode = product.ProductCode,
								Specs = product.Specs,
								Price = product.Price,
								OutboundShipments = salesManagement.OutboundShipments,
								ClientCode = salesManagement.ClientCode,
								ClientName = salesManagement.ClientName,
								State = salesManagement.State,
								RecordedState = salesManagement.RecordedState,
								IsReturn = salesManagement.IsReturn,
								ReturnNumber = salesManagement.ReturnNumber,
								CreatorTime = salesManagement.CreatorTime,
								SaleNum = salesManageDetail.SaleNum,
								Id = salesManagement.Id,
								Unit = product.Unit,
							}).Distinct().ToList();

				if (!string.IsNullOrEmpty(dto.SalesCode))
				{
					list = list.Where(x => x.SalesCode.Contains(dto.SalesCode)).ToList();
				}

				if (!string.IsNullOrEmpty(dto.ProductCode))
				{
					list = list.Where(x => x.ProductCode.Contains(dto.ProductCode)).ToList();
				}

				if (!string.IsNullOrEmpty(dto.ProductName))
				{
					list = list.Where(x => x.ProductName.Contains(dto.ProductName)).ToList();
				}

				if (dto.State > 0)
				{
					list = list.Where(x => x.State == dto.State).ToList();
				}

				//计算总页数
				int totalCount = list.Count();
				int pageCount = (int)Math.Ceiling(totalCount * 1.0 / dto.pageSize);
				list = list.Skip((dto.pageIndex - 1) * dto.pageSize).Take(dto.pageSize).ToList();

				var result = list.MapToList<SalesManagementDtoInpute>();

				return (pageCount, totalCount, Response<List<SalesManagementDtoInpute>>.Ok(result));
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 删除销售管理
		/// </summary>
		/// <param name="info"></param>
		/// <returns></returns>
		public async Task<Response<bool>> DelSalesManagement(SalesManagementDtoInpute info)
		{
			try
			{
				var list = info.MapTo<SalesManagement>();
				var result = await _salesManagementRepository.DeleteByIdAsync(list);
				return result > 0 ? Response<bool>.Ok(result > 0) : Response<bool>.Fail(result > 0);
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 批量删除销售管理
		/// </summary>
		/// <param name="info"></param>
		/// <returns></returns>
		public Task<Response<bool>> BatchDelSearchSalesManagement(SalesManagementDtoInpute dto)
		{
			try
			{
				var sid = dto.DelId.Split(',');
				var list = new List<SalesManagement>();
				foreach (var item in sid)
				{
					var warehouseList = _salesManagementRepository.GetListQuery().Where(x => x.Id == int.Parse(item)).ToList();
					list.AddRange(warehouseList);
				}

				var result = _salesManagementRepository.DeleteAsync(list);
				return result.Result > 0 ? Task.FromResult(Response<bool>.Ok(result.Result > 0)) : Task.FromResult(Response<bool>.Fail(result.Result > 0));
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 查看销售管理
		/// </summary>
		/// <param name="info">要查看的销售管理</param>
		/// <returns></returns>
		public async Task<Response<FillSalesManagement1Dto>> FillSalesManagement1Async(FillSalesManagement1Dto info)
		{
			try
			{
				//var result = _salesManagementRepository.GetListQuery().FirstOrDefault(x => x.Id == info.Id);

				//var list = result.MapTo<FillSalesManagement1Dto>();

				//return list != null ? Response<FillSalesManagement1Dto>.Ok(list) : Response<FillSalesManagement1Dto>.Fail("失败");


				var salesManagement = _salesManagementRepository.GetListQuery().FirstOrDefault(x => x.Id == info.Id);

				var result = new FillSalesManagement1Dto
				{
					Id = salesManagement.Id,
					ProductId = salesManagement.ProductId,
					ClientCode = salesManagement.ClientCode,
					ClientName = salesManagement.ClientName,
					Creator = salesManagement.Creator,
					CreatorTime = salesManagement.CreatorTime,
					Delivery = salesManagement.Delivery,
					DocumentType = salesManagement.DocumentType,
					SalesCode = salesManagement.SalesCode,
					Phone = salesManagement.Phone,
					State = salesManagement.State,
					Remarks = salesManagement.Remarks,
					OrdersSum = salesManagement.OrdersSum,
				};

				result.FileSalesManagement2DtoList = (from a in Db.SalesManagement
													  join b in Db.SalesManageDetail on a.SalesCode equals b.SalesCode
													  join c in Db.Product on b.ProductId equals c.Id
													  where a.Id == info.Id
													  select new FileSalesManagement2Dto
													  {
														  ProductCode = c.ProductCode,
														  ProductName = c.ProductName,
														  Specs = c.Specs,
														  Price = c.Price,
														  SaleNum = b.SaleNum,
														  Unit = c.Unit,
														  Id = a.Id,
														  ReturnNumber = a.ReturnNumber
													  }).ToList();

				return Response<FillSalesManagement1Dto>.Ok(result);
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 查看销售下的产品管理
		/// </summary>
		/// <param name="info"></param>
		/// <returns></returns>
		//public async Task<Response<List<FileSalesManagement2Dto>>> FileSalesManagement2DtoAsync(FileSalesManagement2Dto info)
		//{
		//	try
		//	{
		//		var result = _productRepository.GetListQuery();
		//		var resultt = _salesManageDetailRepository.GetListQuery().FirstOrDefault(x=>x.ProductId == info.Id);
		//		var list = _salesManagementRepository.GetAllListAsync();

		//		var result1 = (from product in result
		//					   join salesManageDetail in resultt 
		//					   on product.Id equals salesManageDetail.ProductId
		//					   join salesManagement in list
		//					   on salesManagement.SalesCode equals salesManageDetail.SalesCode
		//					   select new FileSalesManagement2Dto
		//					   {
		//						   ProductName = product.ProductName,
		//						   ProductCode = product.ProductCode,
		//						   Id = product.Id,
		//						   Price = product.Price,
		//						   Specs = product.Specs,
		//						   SaleNum = salesManageDetail.SaleNum,
		//						   Unit = product.Unit,
		//					   }).ToList();

		//		return Response<List<FileSalesManagement2Dto>>.Ok(result1);
		//	}
		//	catch (Exception)
		//	{
		//		throw;
		//	}
		//}

		/// <summary>
		/// 添加销售管理 + 产品列表
		/// </summary>
		/// <param name="info">要添加的销售管理实体</param>
		/// <returns></returns>
		public async Task<Response<bool>> AddSalesManagement(AddSalesManagementDto info)
		{
			try
			{
				var result = new SalesManagement
				{
					SalesCode = info.SalesCode,
					ClientCode = info.ClientCode,
					ProductId = 1,
					ClientName = info.ClientName,
					Phone = info.Phone,
					Delivery = info.Delivery,
					Remarks = info.Remarks,
					Creator = info.Creator,
					CreatorTime = info.CreatorTime,
					RecordedState = info.RecordedState = false,
					State = info.State = 1,
					IsReturn = info.IsReturn = true,
					DocumentType = info.DocumentType = "1",
					OrdersSum = info.OrdersSum,
				};

				int i = 0;
				using (IDbContextTransaction tran = Db.Database.BeginTransaction())
				{
					try
					{
						i = await _salesManagementRepository.InsertAsync(result);
						var list = new List<SalesManageDetail>();
						foreach (var item in info.FileSalesManagement2Dto)
						{
							list.Add(new SalesManageDetail
							{
								SalesCode = info.SalesCode,
								ProductId = 1,
								SaleNum = item.SaleNum
							});
						}
						await _salesManageDetailRepository.InsertAsync(list);
						tran.Commit();
						return i > 0 ? Response<bool>.Ok(i > 0) : Response<bool>.Fail(i > 0);
					}
					catch (Exception)
					{
						tran.Rollback();
						throw;
					}
				}
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 销售编号
		/// </summary>
		/// <returns></returns>
		public async Task<Response<List<SaleDtos>>> BindSale()
		{
			var list = await _customerRepository.GetAllListAsync();
			var result = list.MapToList<SaleDtos>();
			return Response<List<SaleDtos>>.Ok(result);
		}
		/// <summary>
		/// 智能联想框
		/// </summary>
		/// <param name="dto"></param>
		/// <returns></returns>
		public Task<Response<CustomsDtos>> GetCustomByCode(SaleDtos dto)
		{
			var Custom = _customerRepository.GetListQuery();
			var customs = _customContactRepository.GetListQuery();

			var list = (from a in Custom
						join b in customs on a.CustomrCode equals b.CustomrCode
						where a.CustomrCode == dto.CustomrCode
						select new CustomsDtos
						{
							Id = a.Id,
							CustomrCode = b.CustomrCode,
							CustomName = a.CustomName,
							Contacts = b.Contacts,
							Phone = a.Phone
						}).FirstOrDefault();
			return Task.FromResult(new Response<CustomsDtos> { Data = list });
		}

		/// <summary>
		/// 销售管理是否退货
		/// </summary>
		/// <param name="info"></param>
		/// <returns></returns>
		public async Task<Response<bool>> IsReturnSearchSalesManagement(SalesManagementDtoInpute info)
		{
			try
			{
				var list = await _salesManagementRepository.GetListQuery().FirstOrDefaultAsync(x => x.Id == info.Id);

				list.IsReturn = false;

				var result = await _salesManagementRepository.UpdateAsync(list);

				return result > 0 ? Response<bool>.Ok(result > 0) : Response<bool>.Fail(result > 0);
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 销售管理是否入账
		/// </summary>
		/// <param name="info"></param>
		/// <returns></returns>
		public async Task<Response<bool>> IsRecordedSearchSalesManagement(SalesManagementDtoInpute info)
		{
			try
			{
				var list = await _salesManagementRepository.GetListQuery().FirstOrDefaultAsync(x => x.Id == info.Id);

				list.RecordedState = false;

				var result = await _salesManagementRepository.UpdateAsync(list);

				return result > 0 ? Response<bool>.Ok(result > 0) : Response<bool>.Fail(result > 0);
			}
			catch (Exception)
			{
				throw;
			}
		}

		/// <summary>
		/// 销售退货
		/// </summary>
		/// <param name="info"></param>
		/// <returns></returns>
		public async Task<Response<bool>> RefunAdd(SalesReturnDto info)
		{
			var produc = info.SaleDtoss;
			var sale = produc.Select(x => new SalesReturn
			{
				SalesId = info.SalesId,
				SalesReturnCode = info.SalesReturnCode,
				ProductId = x.ProductCode,
				SalesReturnNumber = info.SalesReturnNumber,
				SalesReturnSum = x.SalesReturnSum,
				ClientName = info.ClientName,
				SalesReturnState = info.SalesReturnState = false,
				State = info.State = 1,
				CreateTime = DateTime.Now,

			}).DistinctBy(x => x.Id).ToList();
			KeyEntity key = new KeyEntity();
			key.Id = info.Id;

			using (var tran = Db.Database.BeginTransaction())
			{
				var j = await _salesReturnRepository.InsertAsync(sale);
				if (j > 0)
				{

					var procue = await _salesManagementRepository.GetEntityByIdAsync(key);
					if (procue != null)
					{
						procue.IsReturn = true;
						var i = await _salesManagementRepository.UpdateAsync(procue);

						Db.MessageCenter.Add(new MessageCenter
						{
							MsgTitle = "销售管理",
							MsgContent = "已完成销售",
							MsgType = "出库审核",
							MsgState = "未读",
							MsgTime = DateTime.Now.ToString(),
						});
						var x = Db.SaveChanges();
						if (i > 0)
						{
							tran.Commit();
							return Response<bool>.Ok(true);
						}
						else
						{
							tran.Rollback();
							return Response<bool>.Fail("退货失败");
						}
					}
					else
					{
						tran.Rollback();
						return Response<bool>.Fail("退货失败");
					}
				}
				else
				{
					tran.Rollback();
					return Response<bool>.Fail("退货失败");
				}
			}
		}
	}
}
